<?php

namespace App\Jobs;

use Exception;
use Throwable;
use App\Models\Mysql\XnOrder;
use Illuminate\Bus\Queueable;
use App\Models\Admin\Supplier;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use App\Models\Mysql\CombinedOrders;
use Illuminate\Queue\SerializesModels;
use App\Recharge\Traits\RechargeTraits;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Jobs\Middleware\SupplierDbConnectCheck;
use App\Recharge\Exceptions\CyclePunch\OrderNotFoundException;


class ZuheJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, RechargeTraits;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(public Supplier $supplier, public XnOrder $order){}

    /**
     * @return array
     */
    public function middleware(): array
    {
        return [new SupplierDbConnectCheck($this->supplier)];
    }

    /**
     * @return void
     * @throws Throwable
     */
    public function handle(): void
    {
        $stateList = [];
        try {
            // 查询所有的组合订单
            $orders = CombinedOrders::s($this->supplier)->where('order_no', $this->order->order_sn)->get();
            if ($orders->isEmpty()) {
                throw new OrderNotFoundException($this->order->order_sn, "没有找到组合订单列表");
            }
            $stateList = $orders->pluck('state')->toArray();
            if (in_array(0, $stateList)) {
                throw new Exception('还有未充值的订单,无法进行下一步');
            }
            $unique = array_values(array_unique($stateList));
            if (count($unique) != 1) {
                throw new Exception('订单不是全部成功或者全部失败');
            }
            OrderCallbackNotify::dispatch($this->supplier, $this->order, $unique[array_key_first($unique)] == 1)->onQueue('merchant_notify');

        } catch (Throwable $e) {
            Log::channel('job')->error('组合job失败', [
                'supplier'  => $this->supplier->toArray(),
                'order'     => $this->order->toArray(),
                'states'    => $stateList,
                'error'     => error2array($e),
            ]);
        }
    }
}

